
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/details/box_details_page.dart';
import 'package:nft_shop/market/page/details/works_details_page.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/order/my_resell_page.dart';
import 'package:nft_shop/my/page/write/my_works_creation_page.dart';
import 'package:nft_shop/my/view/my_check_work_widget.dart';
import 'package:nft_shop/my/view/my_editor_works_bottom.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/image_util.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CheckWorkPage extends StatefulWidget {
  String id;
  CheckWorkPage({Key? key,required this.id}) : super(key: key);

  @override
  _CheckWorkPageState createState() => _CheckWorkPageState();
}

class _CheckWorkPageState extends State<CheckWorkPage> with AutomaticKeepAliveClientMixin{
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
  RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;


  //获取数据
  Future<List> loadData({int? pageNum}) async {
    return await ServiceRepository.specialListByAlbumId(
        page: pageNum!,
        pageSize: pageSize,id: widget.id);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "查看作品",
      ),
      body:SmartRefresher(
          controller: refreshController,
          header: WaterDropHeader(),
          footer: ClassicFooter(),
          onRefresh: refresh,
          onLoading: loadMore,
          enablePullUp: true,
          child: _gridViewWidget()
      ),
    );
  }

  ///我的
  Widget _gridViewWidget() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }
    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      physics: BouncingScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 15,
        mainAxisSpacing: 15,
        childAspectRatio: 167 / 230,
      ),
      //maxCrossAxisExtent
      itemBuilder: (context, index) {
        return _itemWidget(list[index]);
      },
      itemCount: list.length,
    );
  }

  ///item
  Widget _itemWidget(MyGoodsSpecialModel model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    //index 0我的拥有 1我的卖出 2我的创作 3售卖中
    //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
    //special_cast_status铸造状态 1未铸造 2铸造中 3已铸造
    //goods_status状态: 0待上架 1正在出售 2被买家锁定 3买家已支付 4.超时 5已取消
    //special_sell_status 转售状态 1是0否
    String showType = "";
    if(model.specialCastStatus == 1){
      showType = "未铸造";
    }else if(model.specialCastStatus == 2){
      showType = "铸造中";
    }else if(model.specialCastStatus == 3){
      showType = "已铸造";
    }

    return InkWell(
      // onTap: () => Get.to(WorksDetailsPage(id:model.goodsId!,)),
      // onTap: () => Get.to(MyResellPage(model: model,)),
      onTap: (){},
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
              )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: LoadImage(
                    model.thumb ?? "",
                    width: double.infinity,
                    height: itemHeight,
                  ),
                ),
                Positioned(
                  left: 9,
                  top: 8,
                  child: _objectState(showType),
                ),
                Positioned(
                  bottom: 5,
                  left: 5,
                  child: _objectType(
                    model.specialTypeName ?? "",
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 7),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(9),
                              child: LoadImage(
                                model.portrait ?? "",
                                width: 18,
                                height: 18,
                                holderImg: "header_img",
                              ),
                            ),
                            SizedBox(
                              width: 4,
                            ),
                            Text(
                              model.nickname ?? "",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Global.kTheme.textPrimary0,
                                  fontFamily: Global.mySemiboldFont),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 2,
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  ///藏品状态
  Widget _objectState(String state) {
    Color color = Color(0xFF50E3C2);
    return Container(
        height: 24,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: Global.kTheme.colorBackground3.withAlpha(100),
        ),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        child: Text(
          state,
          style: TextStyle(
              color: Global.kTheme.textPrimary5,
              fontSize: 12,
              fontFamily: Global.mySemiboldFont),
        ));
  }

  ///藏品类型
  Widget _objectType(String state) {
    return Container(
      height: 17,
      decoration: BoxDecoration(
        color: Global.kTheme.colorBackground3,
      ),
      padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      child: Text(
        state,
        style: TextStyle(
            color: Global.kTheme.textPrimary5,
            fontSize: 10,
            fontFamily: Global.mySemiboldFont),
      ),
    );
  }
}
